from flask import Blueprint, request, jsonify
from models.entity.sensor import Sensor
import json
from models.entity.device_with_sensor import DeviceWithSensor
from utils.result import result

"""
这个文件完成的是对传感器的管理，实现对传感器的添加，删除和修改,查看
"""
mod = Blueprint("core_sensor", __name__, url_prefix="/core/sensor", template_folder="templates",
                static_folder="static")

@mod.route('/get_all/', methods=['GET', 'POST'])
def get_all():
    """得到传感器"""
    """传入的是设备的id"""
    """
    {

    }
    """
    # try:
    #     dict = json.loads(request.data.decode("utf-8"))
    # except:
    #     return result(success=0, error_code=-1, error_msg="json格式错误")
    sensors = Sensor.get_all_sensors()
    t_list = [item.to_dict() for item in sensors]
    return result(success=1, data=t_list)





@mod.route('/get_all_by_device_id/', methods=['GET', 'POST'])
def get_sensor_by_device():
    """得到传感器"""
    """传入的是设备的id"""
    """
    {
        "id": 2
    }
    """
    try:
        dict = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    sensors = Sensor.get_sensors_by_device_id(dict['id'])
    t_list = [item.to_dict() for item in sensors]
    return result(success=1, data=t_list)


@mod.route('/get_all_by_sensor_type_id/', methods=['GET', 'POST'])
def get_sensor_by_device_id():
    """得到传感器"""
    """传入的是传感器类型的id"""
    """
    {
        "id": 2
    }
    """
    receive = request.data
    try:
        dict = json.loads(receive.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    sensors = Sensor.query.filter_by(sensor_type_id=dict["id"]).order_by('dis_order').all()
    t_list = [item.to_dict() for item in sensors]
    return result(success=1, data=t_list)


@mod.route('/get_all_by_sensor_group_id/',methods=["POST"])
def get_all_by_sensor_group_id():
    """
    根据传感器分组id获取此分组下的所有传感器
    """
    
    """
    {
        "id":id    // 传感器分组id
    }
    """
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    all_sensor=Sensor.query.filter_by(sensor_group_id=data["id"]).all()
    t_list = [item.to_dict() for item in all_sensor]
    return result(success=1, data=t_list)


@mod.route('/del/', methods=['GET', 'POST'])
def del_sensor():
    """删除传感器"""

    """
    {
    "id":2
    }
    """
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    sensor = Sensor.get_sensor_by_id(data["id"])
    if not sensor:
        return result(success=0, error_code=-1, error_msg="没有查找到当前记录")
    # 删除sensor与device的中间表信息
    for item in DeviceWithSensor.query.filter_by(sensor_id=sensor.id).all():
        if item.delete() is False:
            return result(success=0, error_code=-3, error_msg="未知错误")
    if sensor.delete():
        return result(success=1)
    else:
        return result(success=0, error_code=-3, error_msg="未知错误")


@mod.route('/add/', methods=['GET', 'POST'])
def add_sensor():
    """
    {
    "name":"kddd12dk",
    "sensor_type_id":1,
    "sensor_group_id":1
    "code":"dddhttd",
    "eng_unit":"ggg",
    "description":"fff",
    "address":"太原"
    "tag_type":"# io 或者memory
    "client_access": # r或者 rw,就是读,或者读写
    "scan_rate": # 扫描周期,int类型
    "icon": 图标
    "status":1,
    "dis_order":3,
    "data_type": data_type的值:boolean, int16 ,int32, in64 ,float
    "al_h":900,
    "al_l":10,
    "al_hh":950,
    "al_ll":5,
    "eng_max":1000,
    "eng_min":10,
    "topic":主题
    "client_id":1 # 网关id
    "is_exp":0或者1, 是否存在表达式, 1:存在,0:不存在
    "exp": 表达式
    "alarm":是否是报警传感器,1:是,0:不是
    }
    """
    try:
        dict = json.loads(request.data.decode("utf-8"))
        print('dict', dict)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    if Sensor.get_sensor_by_name(dict["name"]):
        return result(success=0, error_code=-1, error_msg="传感器名称已存在")
    if Sensor.get_sensor_by_code(dict["code"]):
        return result(success=0, error_code=-1, error_msg="传感器编码已存在")
    if "id" in dict:
        dict.pop("id")
    sensor = Sensor()
    try:
        sensor.from_dict(dict)
    except RuntimeError as e:
        return result(success=0, error_code=-1, error_msg=str(e))
    if sensor.save():
        return result(success=1)
    else:
        return result(success=0, error_code=-3, error_msg="未知错误")


@mod.route('/edit/', methods=['GET', 'POST'])
def edit_sensor():
    """这个函数的主要功能是编辑传感器"""
    """
    {
    "name":"kddd12dk",
    "sensor_type_id":1,
    "code":"dddhttd",
    "description":"fff",
    "status":1,
    "dis_order":3,
    "h":900,
    "l":10,
    "hh":950,
    "ll":5,
    "range_max":1000,
    "range_min":0,
    "eng_unit":"ggg",
    "source_addr":"192.162.0.4"
    }
    """
    try:
        dict=json.loads(request.data.decode("utf-8"))
        print('dict', dict)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    sensor = Sensor.get_sensor_by_id(dict["id"])
    if not sensor:
        return result(success=0, error_code=-1, error_msg="当前操作的记录不存在")
    print('dict["name"]', dict["name"], 'sensor.name', sensor.name)
    if dict["name"] != sensor.name and Sensor.get_sensor_by_name(dict["name"]) is not None:
        return result(success=0, error_code=-1, error_msg="传感器名称已存在")
    print('dict["code"]', dict["code"], 'sensor.code', sensor.code)
    if dict["code"] != sensor.code and Sensor.get_sensor_by_code(dict["code"]) is not None:
        return result(success=0, error_code=-1, error_msg="传感器编码已存在")
    try:
        sensor.from_dict(dict)
    except RuntimeError as e:
        return result(success=0, error_code=-1, error_msg=str(e))
    if sensor.save():
        return result(success=1)
    else:
        return result(success=0, error_code=-3, error_msg="未知错误")


# @mod.route('/get_all/', methods=['GET', 'POST'])
# def get_dict_item():
#     """得到全部传感器"""
#     """这个方法不合理"""
#     """无需传参"""
#     sensors = Sensor.query.all()
#     t_list = [item.to_dict() for item in sensors]
#     return result(success=1,data=t_list)

@mod.route("/search/",methods=["POST"])
def search_sensor():
    """
    模糊查询
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    try:
        dict = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    tmp ={}
    data =[]
    if 'query_word' in dict:
        query_word = dict['query_word']
    else:
        tmp['success'] = 0
        tmp['error_code'] = -9
        tmp['error_msg'] = "数据格式错误"
        tmp['data'] = data
        return jsonify(tmp)
    sensor = Sensor.search(query_word)
    return jsonify(sensor)

######更新所有设备下的传感器
@mod.route("/update_sensor_to_device/", methods=["GET", "POST"])
def update_sensor_to_device():
    """
        {
        "device_id":1
        "sensors" [1,3 ...]
        }
        """
    if request.method == 'POST':
        try:
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
        except:
            error_msg = {
                "success": 0,
                "error_code": -1,
                "error_msg": "json格式错误"
            }
            return jsonify(error_msg)
        device_id = data['device_id']
        sensor_ids = data['sensors']
        connectors = DeviceWithSensor.query.filter_by(device_id=device_id).all()
        for item in connectors:
            # print(222,item) ,加上这个就报错 'ProjectItemWithSensor' object has no attribute 'project_id',有时间研究
            if item.delete() != 0:
                return jsonify('删除错误')
        print('删除成功')
        DeviceWithSensor.add_sensors_to_device(device_id, sensor_ids)
        return result(data=[])

# @mod.route("/alarm/",methods=["POST"])
# def search_sensor():
#     """
#     模糊查询
#     """
#     # request: json
#     # {
#     #      {"Topic":"/1401010010001/M1304","Type":0,"Level":0,"Context":{"Msg":"超限报警,值500.上限450,下限330"},
#     #          "SerialId":"1538028110634","Time":"2018-09-27T14:01:50.634325+08:00"}
#     # }
#     try:
#         data = json.loads(request.data.decode("utf-8"))
#     except:
#         return result(success=0, error_code=-1, error_msg="json格式错误")

